import api from './api.js';

export default{
    template: `
        <el-table :data="menuData" style="width: 100%">
            <el-table-column prop="name" label="菜名"></el-table-column>
            <el-table-column prop="description" label="简介"></el-table-column>
            <el-table-column prop="image" label="图片"></el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column label="购买">
                <template #default="scope">
                <el-button type="primary" @click="addToCart(scope.$index, scope.row)">添加</el-button>
                </template>
            </el-table-column>
            <!-- 其他列... -->
        </el-table>
                    
    `,
    props: ['userInfo', 'isLoggedIn'],
    data() {
      return {
        orderId: 0,
        menuData: [],
      };
    },
    async created() {
        const resp = await api.getDishes();
        // console.log(resp.data);
        let dishes = resp.data.data;
        for (let dish of dishes) {
          this.menuData.push(dish);
        }
        if (this.isLoggedIn) {
          this.updateOrderId();
      }
    },
    methods: {
        async addToCart(index, row) {
            if (!this.isLoggedIn) {
                this.$message.error('请先登录');
                return;
            }
            const orderId = this.orderId; // 你需要提供一个orderId
            const dish = row;
            console.log(dish);
            console.log(dish.dishId);
            try {
              await api.addOrderDish(orderId, dish.dishId);
              this.$message.success('菜品已成功添加到购物车');
            } catch (error) {
              this.$message.error('添加菜品到购物车失败');
            }
        },
        async updateOrderId() {
          api.getOrdersByStatus(this.userInfo.id, 1)
                .then(response => {
                    console.log(response)
                    console.log(response.data)
                    console.log(response.data.data);
                    if (response.data.data != null) {
                        this.orderId = response.data.data[0].orderId;
                        console.log(this.orderId);
                    } else {
                        api.createOrder(this.userInfo.id)
                          .then(response => {
                              console.log(response.data);
                              this.orderId = response.data.data.orderId;
                              console.log(this.orderId);
                          })
                          .catch(error => {
                              console.error(error);
                          });
                    }
                })
          }
    },
    watch: {
      isLoggedIn() {
        this.updateOrderId();
        console.log(this.orderId);
      }
    }
};